use ggez::{glam::Vec2, Context, graphics, mint::Point2};
use rand::Rng;



pub struct Particle {
    location: Vec2,
    velocity: Vec2,
    acceleration: Vec2,

    angle: f32,
    a_velocity: f32,

    size: f32,
    mass: f32,
    
    lifespan: f32,

    param: graphics::DrawParam
}

impl Particle {
    pub fn new(location: Vec2, rot: f32) -> Particle {
        let mut rng = rand::thread_rng();
        let velocity = Vec2{x: rng.gen_range(-1.0..1.0), y: rng.gen_range(-1.0..1.0)};
        let acceleration = Vec2{x: 0.0, y: 0.0};
        let angle = rot;
        let a_velocity = 0.0;
        let size = rng.gen_range(2.0..3.0);
        let mass = size*size*size;
        let lifespan = 0.5;
        let param = graphics::DrawParam::default();
        Particle { location, velocity, acceleration, angle, a_velocity, size, mass, lifespan, param}
    }

    pub fn is_dead(&self) -> bool {
        if self.lifespan <= 0.0 {
            true
        } else {
            false
        }
    }

    pub fn apply_force(&mut self, force: Vec2) -> () {
        self.acceleration += force;
    }

    pub fn update(&mut self) -> () {
        self.acceleration /= self.mass;
        self.velocity += self.acceleration;
        self.location += self.velocity;
        self.lifespan -= 0.01;
        self.acceleration *= 0.0;

        self.a_velocity = self.velocity.x*0.05;
        self.angle += self.a_velocity;
        
        self.param = graphics::DrawParam::default().dest(self.location).rotation(self.angle);
    }

    pub fn display(&mut self, ctx: &mut Context, canvas : &mut graphics::Canvas) -> () {
        let size = self.size * self.lifespan;

        let polygon = graphics::Mesh::new_polygon(
            ctx, 
            graphics::DrawMode::fill(), 
            &[Point2{x: 0.0, y: -3.0*size}, Point2{x: 2.0*size, y: 3.0*size}, Point2{x: 0.0, y: 0.0}, Point2{x: -2.0*size, y: 3.0*size}], 
            graphics::Color::new(0.7, 0.3, 0.0, 1.0)).unwrap();
        canvas.draw(&polygon, self.param); 
        
    }
}